#!/bin/sh

# Inspired by:
# https://bbs.archlinux.org/viewtopic.php?pid=485129#p485129

#
# ~/.xinitrc
#
# Executed by startx (run your window manager from here)
#
# See also ~/.xserverrc

userresources=$HOME/.Xresources
usermodmap=$HOME/.Xmodmap
sysresources=/etc/X11/xinit/.Xresources
sysmodmap=/etc/X11/xinit/.Xmodmap

export XDG_DATA_DIRS="/usr/share:/usr/local/share:$XDG_DATA_DIRS"

if [ -f $sysresources ]; then
    xrdb -merge $sysresources
fi

if [ -f $sysmodmap ]; then
    xmodmap $sysmodmap
fi

if [ -f "$userresources" ]; then
    xrdb -merge "$userresources"
fi

if [ -f "$usermodmap" ]; then
    xmodmap "$usermodmap"
fi

# start some nice programs
if [ -d /etc/X11/xinit/xinitrc.d ] ; then
    for f in /etc/X11/xinit/xinitrc.d/?*.sh ; do
        [ -x "$f" ] && . "$f"
    done
    unset f
fi

WHAT=
if [ -z "$1" ]; then
    WHAT="xterm"
else
    WHAT="$1"
fi
echo "running $WHAT"

case "$WHAT" in
    a|awesome)
	WHAT=awesome
	;;
    openbox)
        WHAT=openbox-session
        ;;
    fluxbox)
        WHAT=startfluxbox
        ;;
    xfce4)
        WHAT=startxfce4
        ;;
    kde)
        WHAT=startkde
        ;;
    gnome)
        WHAT=gnome-session
        ;;
    e|enlightenment)
        WHAT=enlightenment_start
        ;;
    lxde)
        WHAT=startlxde
        ;;
    dwm)
        WHAT=dwm_run
        ;;
    icewm)
        WHAT=icewm-session
        ;;
    *)
        ;;
esac

[[ -x /usr/bin/lxsession ]] && /usr/bin/lxsession &

[[ -x /usr/bin/xscreensaver ]] && /usr/bin/xscreensaver -nosplash -display $DISPLAY &

if [ -n "`pgrep -U $LOGNAME gnome-keyring`" ]; then
    eval $(/usr/bin/gnome-keyring-daemon --start --components=pkcs11,secrets,ssh)
    export SSH_AUTH_SOCK
fi

[[ -x /usr/bin/redshift ]] && [[ -z "`pgrep -U $LOGNAME redshift`" ]] && /usr/bin/redshift&

[[ -x /usr/bin/compton ]] && /usr/bin/compton -d $DISPLAY -b

exec $WHAT >> ~/.cache/xinit_stdout 2>> ~/.cache/xinit_stderr
echo "`basename $0` terminated with status $?"
